<template>
  <div class="text-white">
    <h1 class="text-2xl font-bold mb-6">我的购物车</h1>
    <div v-if="items.length === 0" class="text-white/60">购物车空空如也～</div>
    <div v-else class="grid gap-4">
      <div v-for="(it, idx) in items" :key="it.id" class="flex items-center gap-4 p-4 rounded-xl border border-white/10 bg-white/5">
        <!-- 统一缩略图容器：方形比例，绝对定位填充，避免不同尺寸图片导致行高抖动 -->
        <div class="relative w-20 shrink-0">
          <div class="pt-[100%]"></div>
          <img :src="it.cover || '/images/apple.svg'" :alt="it.name"
               class="absolute inset-0 w-full h-full object-cover rounded-lg"
               loading="lazy" decoding="async" referrerpolicy="no-referrer" draggable="false"
               @error="(e)=> e.target.src = '/images/apple.svg'" />
        </div>
        <div class="flex-1">
          <div class="font-medium">{{ it.name }}</div>
          <div class="text-emerald-400 font-bold">￥{{ it.price }}</div>
        </div>
        <div class="flex items-center gap-2">
          <button class="px-3 py-1 rounded-full border border-white/10 bg-white/5" @click="dec(idx)">-</button>
          <span>{{ it.qty }}</span>
          <button class="px-3 py-1 rounded-full border border-white/10 bg-white/5" @click="inc(idx)">+</button>
        </div>
        <button class="text-red-400" @click="remove(idx)">删除</button>
      </div>
      <div class="flex items-center justify-between mt-4">
        <div class="text-white/70">共 {{ totalQty }} 件商品</div>
        <div class="text-xl font-extrabold text-emerald-400">合计：￥{{ totalPrice.toFixed(2) }}</div>
      </div>
      <button class="btn-primary w-full text-center" @click="goCheckout">去结算</button>
    </div>
  </div>
</template>

<script>
// 使用 Vue2 风格（Options API）重写：更易读，便于维护
import toast from '../composables/toast'
import { createOrder } from '@/api/orderApi.js'
import { useAuthStore } from '../stores/auth'

export default {
  name: 'CartPage',
  data(){
    return {
      // 购物车条目：[{ id, name, price, cover, qty }]
      items: []
    }
  },
  computed: {
    // 总件数
    totalQty(){ return this.items.reduce((s,x)=> s + x.qty, 0) },
    // 总价（未含运费/折扣）
    totalPrice(){ return this.items.reduce((s,x)=> s + x.qty * x.price, 0) }
  },
  mounted(){
    // 初次加载购物车
    this.load()
    // 监听来自其他组件/页面的更新事件，实现跨组件同步
    window.addEventListener('cart-updated', this.load)
  },
  beforeUnmount(){
    window.removeEventListener('cart-updated', this.load)
  },
  methods: {
    // 从本地读取购物车
    load(){
      try{
        const raw = JSON.parse(localStorage.getItem('cart') || '[]')
        this.items = (Array.isArray(raw) ? raw : []).map(it => ({
          id: it.id,
          name: it.name,
          price: Number(it.price) || 0,
          cover: it.cover,
          qty: it.qty
        }))
      }catch(_){ this.items = [] }
    },
    // 写回与广播
    persist(){
      localStorage.setItem('cart', JSON.stringify(this.items))
      window.dispatchEvent(new CustomEvent('cart-updated'))
    },
    // 数量 +1（下限为 1）
    inc(i){ this.items[i].qty++; this.persist() },
    // 数量 -1（不得小于 1）
    dec(i){ this.items[i].qty = Math.max(1, this.items[i].qty - 1); this.persist() },
    // 删除某一项
    remove(i){ this.items.splice(i, 1); this.persist(); toast.info('已删除该商品') },
    // 预创建订单并跳转结算
    async goCheckout(){
      const auth = useAuthStore()
      if(!auth.user?.id){ toast.error('请先登录'); return }
      if(this.items.length===0){ toast.error('购物车为空'); return }
      // 不在购物车页预下单，直接进入结算页；订单号将由结算页在支付前创建
      this.$router.push('/checkout')
    }
  }
}
</script>